package org.lucene;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.AtomicReader;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.OpenBitSet;
import org.apache.lucene.util.Version;

public class DoTerm {

	static Random rand;

	public static OpenBitSet getRandomSet(int sz, int bitsToSet) {
		OpenBitSet bs = new OpenBitSet(sz);
		if (sz == 0)
			return bs;
		for (int i = 0; i < bitsToSet; i++) {
			bs.fastSet(rand.nextInt(sz));
		}
		return bs;
	}

//	private  void init(IndexReader reader,String field) throws CorruptIndexException, IOException{
//        int maxDoc = reader.maxDoc();
//        
//        
//        TermDocsEnum termDocs = reader.termDocs();
//        TermEnum termEnum = reader.terms(new Term(field, ""));
// 
//        
//        try {
//            do {
//                
//                Term term = termEnum.term();
//                if (term==null || term.field() != field){
//                   break;
//                }
//                    
//                String termval = term.text();
//                
//             
//                termDocs.seek(termEnum);
//                while (termDocs.next()) {
//                   int docid=termDocs.doc());
//                }
//                
//                
//            } while (termEnum.next());
//        } finally {
//            termDocs.close();
//            termEnum.close();
//        }
//        
//    }
	
	
	/**
	 * @param args
	 * @throws IOException
	 * @throws ParseException
	 */
	public static void main(String[] args) throws IOException, ParseException {
		String indexPath = "D:/index";
		String fieldName = "path";
		String fieldValue = "kong.net";
		String q = "*:*";
		TermsEnum termsEnum = null;

		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexPath)));
		IndexSearcher searcher = new IndexSearcher(reader);
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
		QueryParser parser = new QueryParser(Version.LUCENE_41, fieldName, analyzer);
		Query query = parser.parse(q);
		searcher.search(query, null, 100);
		TopDocs results = searcher.search(query, 5 * 20);
		ScoreDoc[] hits = results.scoreDocs;
		int numTotalHits = results.totalHits;
		System.out.println(numTotalHits + " total matching documents");
		TopDocs search = searcher.search(query, numTotalHits);
		hits = search.scoreDocs;
//		System.out.println(hits.length);
		Document doc = searcher.doc(hits[1].doc);
		String id = doc.get("path");
		System.out.println("doc.get:"+id);
		
		
		Terms termVector = reader.getTermVector(hits[1].doc, fieldName);
		
		System.out.println("termVector Start....");
		if (termVector!=null){
			TermsEnum iterator = termVector.iterator(null);
			if (iterator!=null){
				BytesRef next;
				while ((next = iterator.next()) != null) {
					BytesRef spare = new BytesRef();
					spare.copyBytes(next);
					 System.out.println(new String(spare.bytes));
					System.out.println(iterator.next().utf8ToString());

				}
			}
		}else{
			System.out.println("termVector null!");
		}
			
	
		System.out.println("termVector End....");
		
		
	
		// IndexReaderContext topLevelContext = reader.getContext();
		// List<AtomicReaderContext> leaves = topLevelContext.leaves();
		// OpenBitSet bs = getRandomSet(reader.maxDoc(),
		// rand.nextInt(reader.maxDoc() + 1));

		AtomicReader atomicReader = SlowCompositeReaderWrapper.wrap(reader);
		
		
		Fields lfields = atomicReader.fields();
		lfields.terms(fieldName);
		// need to read org.apache.solr.handler.component.TermsComponent


		Fields fields = MultiFields.getFields(atomicReader);
		System.out.println();
		System.out.println("getFields start...");
		for (String f : fields) {
			System.out.println("FieldName:"+f);
		}
//		Terms terms = reader.getTermVector(0, fieldName);
		
		System.out.println("getFields End...");
		System.out.println();
		String[] fn = {"path","contents"};
//		Terms terms = MultiFields.getTerms(reader, "path");
		Terms terms = atomicReader.terms(fieldName);
		
		Bits liveDocs = atomicReader.getLiveDocs();
		
		System.out.println(terms.getDocCount());
		if (terms != null) {
			termsEnum = terms.iterator(null);
			if (termsEnum == null) {
				System.out.println("termsEnum null");
			} else {
				
					BytesRef next;
					while ((next = termsEnum.next()) != null) {
						DocsEnum docs = termsEnum.docs(liveDocs, null);
						for (int i = 0; i < termsEnum.docFreq(); i++) {
							System.out.println("docID:" + docs.nextDoc());
						}
						
						
//						int nextDoc = docs.nextDoc();
//						while(nextDoc != docs.NO_MORE_DOCS){
//							System.out.println("docs.docID:" + nextDoc);
//							nextDoc = docs.nextDoc();
//						}
//						System.out.println("docs.docID:" + nextDoc);
//						System.out.println("docs.docID2:" + (nextDoc==docs.NO_MORE_DOCS));
						BytesRef spare = new BytesRef();
						spare.copyBytes(next);
//						 System.out.println(new String(spare.bytes));
						System.out.println(termsEnum.next().utf8ToString() + " " + termsEnum.docFreq());

					}


			}

		} else {
			termsEnum = null;
			System.out.println("null");
		}

//		int minNumDocs = (int) (1 * (float) reader.numDocs());
//		System.out.println(minNumDocs);

		reader.close();
	}
}
